#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : combox.py
@Author  : Link
@Time    : 2023/5/14 21:40
@Mark    : 
"""

# 自定义下拉复选框
from typing import List

from PySide2.QtWidgets import QComboBox, QListWidget, QCheckBox, QListWidgetItem, QLineEdit
from PySide2.QtGui import Qt
from PySide2.QtCore import Signal

from ui_component.ui_app_variable import UiGlobalVariable


class ComboCheckBox(QComboBox):
    # 有item被选择时，发出信号
    itemChecked = Signal(list)
    # 保存QCheckBox控件
    _checks = None

    def __init__(self, parent) -> None:
        super().__init__(parent)
        listwgt = QListWidget(self)
        self.setView(listwgt)
        self.setModel(listwgt.model())
        lineEdit = QLineEdit(self)
        lineEdit.setReadOnly(True)
        self.setLineEdit(lineEdit)
        self._checks = []
        # # 预设'全选'
        # self.add_item('全选')

    def add_item(self, check: QCheckBox):
        check.stateChanged.connect(self.on_state_changed)
        self._checks.append(check)
        item = QListWidgetItem(self.view())
        # 设置item不可选中(只可以被Check)
        item.setFlags(item.flags() & Qt.IntersectsItemShape)
        self.view().addItem(item)
        self.view().setItemWidget(item, check)
        self.on_state_changed(None)

    def add_items(self, texts: list, default_select: List[str] = None):
        for text in texts:
            check = QCheckBox(text, self.view())
            if default_select is not None and text in default_select:
                check.setCheckState(Qt.Checked)
            self.add_item(check)

    def clear(self):
        self.view().clear()

    def get_selected(self):
        sel_data = []
        for chk in self._checks:
            # if self._checks[0] == chk:
            #     continue
            if chk.checkState() == Qt.Checked:
                sel_data.append(chk.text())
        return sel_data

    # def set_all_state(self, state):
    #     for chk in self._checks:
    #         chk.blockSignals(True)
    #         chk.setCheckState(Qt.CheckState(state))
    #         chk.blockSignals(False)

    def on_state_changed(self, state):

        # if self.sender() == self._checks[0]:
        #     self.set_all_state(state)

        sel_data = self.get_selected()
        self.itemChecked.emit(sel_data)
        self.lineEdit().setText(';'.join(sel_data))
